package com.itheima.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.common.entity.PageResult;
import com.itheima.common.entity.QueryPageBean;
import com.itheima.common.entity.Result;
import com.itheima.mapper.CheckGroupDao;
import com.itheima.mapper.CheckItemDao;
import com.itheima.pojo.CheckGroup;
import com.itheima.pojo.CheckItem;
import com.itheima.service.CheckGroupService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

@Service
public class CheckGroupServiceImpl implements CheckGroupService {
    @Autowired
    private CheckGroupDao checkGroupDao;
    @Autowired
    private CheckItemDao checkItemDao;

    @Override
    @Transactional
    public void add(CheckGroup checkGroup, List<Integer> checkitemIds) {
        // 向检查组表插入数据
        checkGroupDao.add(checkGroup);

        //获取检查组表id
        Integer checkGroupId = checkGroup.getId();

        // 向中间表插入数据
        checkitemIds.forEach(checkitemId -> {
            checkGroupDao.addCheckGroupAndCheckItem(checkGroupId, checkitemId);
        });
    }

    @Override
    public void deleteById(Integer id) {
        checkGroupDao.deleteById(id);
    }

    @Override
    public List<CheckGroup> findAll() {
        return checkGroupDao.findAll();
    }

    @Override
    public CheckGroup findById(Integer id) {
        return checkGroupDao.findById(id);
    }

    @Override
    public PageResult findPage(QueryPageBean queryPageBean) {
        PageHelper.startPage(queryPageBean.getCurrentPage(), queryPageBean.getPageSize());
        Page<CheckGroup> page = checkGroupDao.findPage(queryPageBean);
        return new PageResult(page.getTotal(), page.getResult());
    }

    @Override
    public List<Integer> findCheckGroupIdsBySetmealId(Integer setmealId) {
        return checkGroupDao.findCheckGroupIdsBySetmealId(setmealId);
    }

    @Override
    @Transactional
    public void update(CheckGroup checkGroup, List<Integer> checkitemIds) {
        // 修改检查组表
        checkGroupDao.update(checkGroup);

        //根据检查项id删除检查组检查项关系表
        Integer checkGroupId = checkGroup.getId();
        checkGroupDao.deleteCheckGroupAndCheckItem(checkGroupId);

        // 向中间表插入数据
        checkitemIds.forEach(checkitemId -> {
            checkGroupDao.addCheckGroupAndCheckItem(checkGroupId, checkitemId);
        });
    }


}
